﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class SelfAdaption : MonoBehaviour {
	public InputField aInputField;
	public InputField bInputField;
	public InputField eInputField;
	public Button ConfirmButton;
	public Button nextStepButton;
	public Text tText;
	public Text answerText;

	private float a;
	private float b;
	private float E;
	private int I;
	private float S;
	private float U;
	private float V;
	private float W;
	private float h;
	private float T1;
	private float T2;
	private float t;
	private Stack<float> ST = new Stack<float>();


	private List<Vector2> pointList = new List<Vector2>();
	public DrawTrapezoids drawTrapezoids;

	// Start is called before the first frame update
	void Start() {

	}

	// Update is called once per frame
	void Update() {

	}

	public void ConfirmData() {
		GetData();
		E = E / (b - a);
		I = 0;
		S = 0;
		U = a;
		V = b;

		AddPoint(U);
		AddPoint(V);

		//MarkPoints();
		ConfirmButton.interactable = false;
		nextStepButton.interactable = true;
	}

	public void OneStep() {

		h = V - U;
		T1 = (F(U) + F(V)) * h / 2f;
		W = (U + V) / 2f;
		AddPoint(W);
		T2 = T1 / 2f + h * F(W) / 2f;

		t = Mathf.Abs(T2 - T1);
		tText.text = I.ToString();
		if (t < E / h) {
			S += T2;
			if (I == 0) {
				answerText.text = S.ToString();
				nextStepButton.interactable = false;
			}
			else {
				U = V;
				V = ST.Pop();
				I -= 1;
			}
		}
		else {
			I += 1;
			ST.Push(V);
			V = W;
		}
	}

	void AddPoint(float x) {
		pointList.Add(new Vector2(x, F(x)));
		drawTrapezoids.pointList = pointList;
		drawTrapezoids.UpdateLine();
	}

	void GetData() {
		a = float.Parse(aInputField.text);
		b = float.Parse(bInputField.text);
		E = float.Parse(eInputField.text);
	}

	private float F(float x) {
		if (x == 0) return 0;
		return Mathf.Sin(x) / x * MainControler.Instance.yAxisMagnification;
	}

}
